/**
 * ---------------------------
 * Time: 2017/8/7 20:58.
 * Author: Cangshi
 * View: http://palerock.cn
 * ---------------------------
 */
define(['app', 'zepto'], function (app, $) {
    'use strict';
    app.service('accidentService', function (accidentDao, SafetyAccident, PromiseUtil, failureHolder, ObjectUtils, logger) {
        this.addAccident = function (accident, cb) {
            if (!(accident instanceof SafetyAccident)) {
                throw new TypeError('欲添加的事故不是安全事故实体');
            }
            var errorMessages = accident.checkPropertyFormed();
            if (errorMessages.length > 0) {
                failureHolder.handleFailure('添加安全事故：' + errorMessages.toString(), 403);
                return;
            }
            accidentDao.insertAccident(accident, function (r, e) {
                if (!e.code || e.code != 200) {
                    failureHolder.handleFailure(e.message, e.code);
                } else {
                    cb.call(window, r, e.message);
                }
            });
        };

        /**
         * 查询所有设备
         * @param cb
         * @param sort {object=} 排序
         */
        this.findAllAccidents = function (cb, sort) {
            accidentDao.findAllAccidents(function (r, e) {
                if (!e.code || (e.code != 200 && e.code != 404)) {
                    failureHolder.handleFailure(e.message, e.code);
                } else {
                    var accidents = r;
                    if (sort && sort.sortBy) {
                        accidents = ObjectUtils.sortingArrayByProperty(accidents, sort.sortBy, sort.order);
                    }
                    cb.call(window, SafetyAccident.toSafetyAccident(accidents), e.message);
                }
            });
        };

        /**
         * 通过id查询单个设备
         * @param accidentId
         * @param cb
         * @param errorDo {function=}
         */
        this.findAccidentById = function (accidentId, cb, errorDo) {
            accidentDao.findAccidentById(accidentId, function (r, e) {
                if (!e.code || e.code != 200) {
                    failureHolder.handleFailure(e.message, e.code, errorDo);
                } else {
                    cb.call(window, SafetyAccident.toSafetyAccident(r[0]), e.message);
                }
            });
        };

        /**
         * 删除某一事件
         * @param accidentId
         * @param cb
         */
        this.deleteAccident = function (accidentId, cb) {
            accidentDao.deleteAccident(accidentId, function (r, e) {
                if (!e.code || e.code != 200) {
                    failureHolder.handleFailure(e.message, e.code);
                } else {
                    cb.call(window, r, e.message);
                }
            })
        }
    });
});